import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/customer_info_model.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/image_utils.dart';
import 'package:ls_work/util/utils.dart';

import '../../model/decode_qrcode_model.dart';
import '../../net/response/food/food_menu_list.dart';
import '../../net/response/food/scan_old_data.dart';
import '../../net/response/food/site_list_data.dart';

class ApplySelectFoodViewModel extends BaseViewModel {
  ApplySelectFoodViewModel(BuildContext context,
      {required this.date,
      required this.site,
      required this.orderType,
      required this.foodTime,
      required this.useNumber,
      required this.selectFood,
      required this.totalPrice,
      required this.userWay})
      : super(context);
  final String date;
  final SiteListData site;
  final String orderType;
  final PickerDataWithIdModel foodTime;
  final int useNumber;
  final List<FoodMenuList> selectFood;
  final num totalPrice;
  final PickerDataWithIdModel userWay;

  CustomerInfoModel scanOldModel = CustomerInfoModel();
  DecodeQrcodeModel model = new DecodeQrcodeModel();

  Widget contentWidget() {
    return ListView(
      children: [
        ///餐品内容
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 16,
            ),
            CommonText('餐品内容'),
            Container(
              height: 10,
            ),
            Column(
              children: selectFood
                  .map((e) => Row(
                        children: [
                          (e.imgAttachId == null
                                  ? ImageLoad(
                                      ImageUtils.getImgPath('none'),
                                      width: 70,
                                      height: 70,
                                      isAsset: true,
                                    )
                                  : ImageLoad(
                                      '${HttpApi.imageHead}${e.imgAttachId}',
                                      width: 70,
                                      height: 70,
                                    ))
                              .toRound(borderRadius: 4.borderRadius),
                          Container(
                            width: 10,
                          ),
                          Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              CommonText(e.name),
                              CommonText('x${e.selectNum}'),
                            ],
                          )
                              .addToContainer(
                                  margin: EdgeInsets.symmetric(vertical: 4))
                              .setWeight(1),
                          Center(
                            child: CommonText('¥${e.price}',
                                textSize: 15, fontWeight: FontWeight.bold),
                          )
                        ],
                      ).addToContainer(
                          height: 70, margin: EdgeInsets.only(bottom: 10)))
                  .toList(),
            ),
          ],
        ).addToContainer(
            color: Colors.white, padding: EdgeInsets.symmetric(horizontal: 16)),

        Container(
          height: 10,
        ),

        IconTitleTextWidget(
          '点餐日期',
          text: date.changeTime(format: [mm, '月', dd, '日']),
          showArrow: false,
        ),

        Container(
          height: 10,
        ),

        IconTitleTextWidget(
          '用餐时间',
          text: foodTime.pickName??"",
          showArrow: false,
        ),

        Container(
          height: 10,
        ),

        IconTitleTextWidget(
          '用餐地点',
          text: site.name??"",
          showArrow: false,
        ),

        Container(
          height: 10,
        ),

        IconTitleTextWidget(
          '用餐方式',
          showArrow: false,
          text: userWay.pickName??"",
        ),

        Container(
          height: 10,
        ),

        IconTitleTextWidget(
          '用餐人数',
          text: '${useNumber}人',
          showArrow: false,
        ),
      ],
    );
  }

  Widget bottomWidget() {
    return Row(
      children: [
        Container(
          width: 16,
        ),
        CommonText('¥$totalPrice',
                textColor: Colors.red,
                textSize: 20,
                fontWeight: FontWeight.bold)
            .setWeight(1),
        TextButton(
          onPressed: () {
            scanCode();
          },
          child: CommonText('扫码付款', textColor: Colors.white),
          style: ButtonStyle(
              minimumSize: WidgetStateProperty.all(
                Size(140, double.infinity),
              ),
              backgroundColor: WidgetStateProperty.all(Colours.app_main),
              shape: WidgetStateProperty.all(RoundedRectangleBorder())),
        )
      ],
    ).addToContainer(color: Colors.white, height: 60);
  }

  Future<void> scanCode() async {
    var code = await Utils.scan();
    if(code.isNullOrEmpty()){
      return;
    }
    try{
      var data = await model.decoed(code);
      if (data.typeCode==1) {
        var account  = await scanOldModel.getCardAccount(humanId: data.id.toString());
        if(account.data==null){
          showToast("该长者未开通一卡通账户");
          return;
        }
        var old = await getOldData(data.id!);
        if (old != null) {

          submitOrder(old);
        }
      }else{
        showToast("请扫描长者二维码");
      }
    }catch(e){
      showToast(e.toNetError());
    }
  }

  Future<ScanOldData?> getOldData(String scanCode) async {
    showLoadingDialog();
    try {
      var data = await scanOldModel.getOldData(scanCode);
      hideDialog();


      return data;
    } catch (e) {
      hideDialog();
      return null;
    }
  }

  var format = <String>[yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss];
  ///下单
  Future<void> submitOrder(IFoodOlder old) async {
    showLoadingDialog(msg: '正在提交下单数据...');
    try{
      var orderDate = DateTime.now().toDateStr(format);
      var data = await PostRequest.submitOrder(
        siteId: site.id.toString(),
        elderHumanId: old.selectOldId.toString(),
        orderDate: orderDate,
        useDate: date.changeTime(format: format),
        useTimeSection: foodTime.pickId,
        // useAddr: '123',
        useNum: useNumber.toString(),
        orderModelType: orderType,
        useType: userWay.pickId,
        isWeek: '0',
        goodsList: selectFood.map((e) => {
          "goodsId":e.id,
          "num":e.selectNum
        }).toList(),
      );
      hideDialog();
      if("0"==data['code'].toString()){
        var orderId = data['data']['id'].toString();
        payOrder(orderId);
      }else{
        showToast(data['msg']);
      }
    }catch(e){
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> payOrder(String orderId) async {
    showLoadingDialog(msg: '正在完成支付...');
    try{
      var data = await PostRequest.payOrder(orderId: orderId,type: "1");
      hideDialog();
      if('0'==data['code'].toString()){
        showToast('支付成功');
        sendMessage(SendMessageEvent(MessageConfig.PAY_FOOD_SUCCESS));
        finish();
      }else{
        showToast(data['msg']);
      }
    }catch(e){
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }
}
